import { useEffect, memo, useMemo, useRef } from 'react'
import { useRequest } from 'ahooks'
import { BigChargeOrder, BigChargeOrderStatus, getBigChargeOrderDetail, getChargingHistory } from './services'
import { Badge, Card, Col, Descriptions, Row, Spin } from 'antd'
import { styled } from '@umijs/max'
import dayjs from 'dayjs'
import { Chart } from '@antv/g2'
import { EquipmentType } from '@/pages/station/stubList/services'

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .ant-descriptions-item-label {
    align-items: center !important;
  }
`
type ChartData = {
  time: number
  name: string
  value: number
}
const setChartConfig = (chart: Chart, unit: string) => {
  chart.data([])

  chart
    .line()
    .encode('x', (d: ChartData) => new Date(d.time))
    .encode('y', 'value')
    .encode('color', 'name')
    .encode('shape', 'smooth')
    
  chart.axis({
    y: {
      title: null
    }
  })

  chart.text().style({
    x: '95%', // 像素坐标
    y: -18, // 像素坐标
    text: `单位: ${unit}`,
    textAlign: 'center',
    fontSize: 12,
    textBaseline: 'middle',
    fill: '#aaaaaa'
  })

  chart.render()
}

const BigChargeOrderDetail: React.FC<RoutePageProps> = props => {
  const voltageLine = useRef<Chart>()
  const currentLine = useRef<Chart>()
  const socLine = useRef<Chart>()
  const temperatureLine = useRef<Chart>()
  const { data: res, loading, runAsync } = useRequest(getBigChargeOrderDetail, {manual: true})
  const { runAsync: getChartData } = useRequest(getChargingHistory, {manual: true})

  const data = useMemo((): Partial<BigChargeOrder> => {
    return res?.data || {}
  }, [res])

  const calcValue = useMemo(() => {
    const result: any = {}
    if (!data.id) return result
    if (data.endTime) {
      const endTime = dayjs(data.endTime)
      const beginTime = dayjs(data.beginTime)
      const duration = endTime.diff(beginTime, 'minutes')
      result.chargeDuration = `${duration}分钟`
    }
    switch (data.status) {
      case BigChargeOrderStatus.进行中: result.payStatus = '--'; break
      case BigChargeOrderStatus['完成充电(待支付)']: result.payStatus = <Badge status="error" text="待支付" />; break
      case BigChargeOrderStatus['完成充电(已支付)']: result.payStatus = <Badge status="success" text="已支付" />; break
    }
    return result
  }, [data])

  useEffect(() => {
    voltageLine.current = new Chart({container: 'voltageLine', autoFit: true, height: 340})
    setChartConfig(voltageLine.current, '伏')
    currentLine.current = new Chart({container: 'currentLine', autoFit: true, height: 340})
    setChartConfig(currentLine.current, '安培')
    socLine.current = new Chart({container: 'socLine', autoFit: true, height: 340})
    setChartConfig(socLine.current, '%')
    temperatureLine.current = new Chart({container: 'temperatureLine', autoFit: true, height: 340})
    setChartConfig(temperatureLine.current, '度')
    if (props.params.orderId) {
      runAsync({
        id: props.params.orderId,
        infoType: parseInt(props.params.infoType),
      })
      getChartData({id: props.params.orderId})
        .then(res => {
          const voltageLineData: ChartData[] = []
          const currentLineData: ChartData[] = []
          const socLineData: ChartData[] = []
          const temperatureLineData: ChartData[] = []
          res.data.forEach(item => {
            voltageLineData.push(
              {time: item.time, name: '枪输入电压', value: item.voltage},
              {time: item.time, name: '车端需求电压', value: item.voltageCar},
            )
            currentLineData.push(
              {time: item.time, name: '枪输入电流', value: item.current},
              {time: item.time, name: '车端需求电流', value: item.currentCar},
            )
            socLineData.push(
              {time: item.time, name: 'SOC', value: item.soc},
            )
            temperatureLineData.push(
              {time: item.time, name: '桩温', value: item.tempEquipment},
              {time: item.time, name: '枪温', value: item.tempStub},
              {time: item.time, name: '车温', value: item.tempCar},
            )
          })
          voltageLine.current?.data(voltageLineData)
          voltageLine.current?.render()
          currentLine.current?.data(currentLineData)
          currentLine.current?.render()
          socLine.current?.data(socLineData)
          socLine.current?.render()
          temperatureLine.current?.data(temperatureLineData)
          temperatureLine.current?.render()
        })
    }
  }, [props.params.orderId])

  return (
    <Spin spinning={loading}>
      <Container>
        <div style={{
          padding: '0 24px',
          borderRadius: 6,
          height: 56,
          display: 'flex',
          alignItems: 'center',
          fontSize: 16,
          fontWeight: 'bold',
        }}>{`订单号: ${props.params.orderId}`}</div>
        <Card title='电站信息'>
          <Descriptions column={3}>
            <Descriptions.Item label='电站名称'>{data.stationName || '--'}</Descriptions.Item>
            <Descriptions.Item label='枪编号'>{data.stubId || '--'}</Descriptions.Item>
            <Descriptions.Item label='所在城市'>{data.cityName || '--'}</Descriptions.Item>
            <Descriptions.Item label='设备类型'>{data.stubType ? EquipmentType[data.stubType] : '--'}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title='用户信息'>
          <Descriptions column={3}>
            <Descriptions.Item label='企业名称'>{data.orgName || '--'}</Descriptions.Item>
            <Descriptions.Item label='车牌号'>{data.carPlat || '--'}</Descriptions.Item>
            {/* <Descriptions.Item label='电卡卡号'>{data.stubType || '--'}</Descriptions.Item> */}
            {/* <Descriptions.Item label='Vin码'>{data.cityName || '--'}</Descriptions.Item> */}
            <Descriptions.Item label='车品牌'>{data.carBrand || '--'}</Descriptions.Item>
            <Descriptions.Item label='车型号'>{data.carSeries || '--'}</Descriptions.Item>
            <Descriptions.Item label='用户昵称'>{data.nickname || '--'}</Descriptions.Item>
            <Descriptions.Item label='手机号'>{data.telephone || '--'}</Descriptions.Item>
            {/* <Descriptions.Item label='电卡名称'>{data.stubType || '--'}</Descriptions.Item> */}
          </Descriptions>
        </Card>
        <Card title='充电信息'>
          <Descriptions column={3}>
            <Descriptions.Item label='开始时间'>{data.beginTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='初始SOC'>{data.socBegin || '--'}</Descriptions.Item>
            <Descriptions.Item label='枪充电开始时间'>{data.beginTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='结束时间'>{data.endTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='结束SOC'>{data.socEnd || '--'}</Descriptions.Item>
            <Descriptions.Item label='枪充电结束时间'>{data.endTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='充电状态'>{data.status === BigChargeOrderStatus.进行中 ? '充电中' : '充电完成'}</Descriptions.Item>
            <Descriptions.Item label='停止原因'>{data.endName || '--'}</Descriptions.Item>
            <Descriptions.Item label='充电时长'>{calcValue.chargeDuration || '--'}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Card title='付款详情'>
          <Descriptions column={3}>
            <Descriptions.Item label='支付方式'>{data.orgName ? '企业余额' : '个人余额'}</Descriptions.Item>
            <Descriptions.Item label='支付状态'>{calcValue.result || '--'}</Descriptions.Item>
            <Descriptions.Item label='支付时间'>{data.paymentTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='订单电量(度)'>{data.electric}</Descriptions.Item>
            <Descriptions.Item label='订单电费(元)'>{data.electricFee}</Descriptions.Item>
            <Descriptions.Item label='订单服务费(元)'>{data.serviceFee}</Descriptions.Item>
            <Descriptions.Item label='订单总金额(元)'>{parseFloat(((data.electricFee || 0) + (data.serviceFee || 0)).toFixed(2))}</Descriptions.Item>
            <Descriptions.Item label='抵扣金额(元)'>{data.cutMoney}</Descriptions.Item>
            <Descriptions.Item label='优惠后金额(元)'>{data.discountM}</Descriptions.Item>
            <Descriptions.Item label='实付金额(元)'>{data.realPay}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Row gutter={[24, 24]}>
          <Col span={12}>
            <Card title='电压折线图'>
              <div id='voltageLine'></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='电流折线图'>
              <div id='currentLine'></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='SOC折线图'>
              <div id='socLine'></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='温度折线图'>
              <div id='temperatureLine'></div>
            </Card>
          </Col>
        </Row>
      </Container>
    </Spin>
  )
}

export default memo(BigChargeOrderDetail)
